#include <stdio.h>
#include <stdarg.h>
#include <string.h>
#include "Logger.h"
#include "Define.h"
#include "AiotEntity.h"
#include "MQTT/MQTTError.h"

#define _LOGGER_MAXLEN          (160)
static AiotLogger* aiotLogger = nullptr;

int8_t initGlobalAiotSdkLog() {

    if (aiotLogger != nullptr) {
        return 0;
    }

    aiotLogger = (AiotLogger*)getSystemInterface()->memMalloc(sizeof(AiotLogger));
    memset(aiotLogger,0x00, sizeof(AiotLogger));

    aiotLogger->logLock = getSystemInterface()->createMutex();
    aiotLogger->logBuffer = (char*)getSystemInterface()->memMalloc(_LOGGER_MAXLEN);
    aiotLogger->length = _LOGGER_MAXLEN;
    return 0;
}

void loggerOut(AiotLoggerLevel level,const char* func,uint32_t line,const char* message,...) {

    getSystemInterface()->enterMutex(aiotLogger->logLock);

    int32_t position = snprintf(aiotLogger->logBuffer,(size_t)aiotLogger->length,"[MQTT %s:%d]",func,line);
    position = position >= aiotLogger->length? aiotLogger->length:position;

    if (position < aiotLogger->length) {
        va_list vaList;
        va_start(vaList,message);
        position += vsnprintf(aiotLogger->logBuffer + position,(size_t)(aiotLogger->length - position),message,vaList);
        va_end(vaList);

        position = position >= aiotLogger->length? aiotLogger->length:position;
    }

    if (aiotLogger->logCallback) {
        aiotLogger->logCallback(level,aiotLogger->logBuffer);
    }

    getSystemInterface()->leaveMutex(aiotLogger->logLock);
}

void destroyGlobalAiotSdkLog() {

    void* loggerMutex = aiotLogger->logLock;

    getSystemInterface()->enterMutex(loggerMutex);

    getSystemInterface()->memFree(aiotLogger->logBuffer);

    getSystemInterface()->memFree(aiotLogger);

    getSystemInterface()->leaveMutex(loggerMutex);

    aiotLogger = nullptr;
    getSystemInterface()->destroyMutex(loggerMutex);
}

int32_t UMQTT_SetLoggerCb(AiotLoggerCb cb) {
    aiotLogger->logCallback = cb;
    return aiotSuccess;
}

